import { AppAxiosResponse } from '@/types/http';
import axios, { AxiosError, AxiosRequestConfig, Canceler, InternalAxiosRequestConfig } from 'axios';
import { ref } from 'vue';
import errorHandle from './errorHandle';

const instance = axios.create({
  timeout: 30 * 1000,
  baseURL: '/final'
});

const requestSuccess = (config: InternalAxiosRequestConfig) => {
  return config;
};

const requestError = (err: AxiosError) => {
  return Promise.reject(err);
};
const responseSuccess = (response: AppAxiosResponse) => {
  if(response.data.code !== 200) {
    errorHandle(response);
    return Promise.reject(response);
  }
  return Promise.resolve(response);
};

const responseError = (err: AxiosError) => {
  return Promise.reject(err);
};

instance.interceptors.request.use(requestSuccess, requestError);
instance.interceptors.response.use(responseSuccess, responseError);

export function request<T = any>(config: AxiosRequestConfig): Promise<AppAxiosResponse<T>> {
  const cancel = ref<Canceler>();
  const request = instance({
    ...config,
    cancelToken: new axios.CancelToken((c) => {
      cancel.value = c;
    })
  });
  request.cancel = cancel;
  return request;
}
